<?php

class TopicCommentsModel
{
	private $topicCommentsKeyPrefix  =   'TPC/';
	private $topicFeedKeyPrefix      =   'TPF/';
	private $slaveKey                =   '/slave';
    
	/**
	 * 加入圈子评论动态
	 * @param unknown $feedInfo
	 * @return boolean|Ambigous <unknown, boolean>
	 */
	public function postCommentFeed($feedInfo){
	    if ( intval($feedInfo['tid']) < 1 || intval($feedInfo['eUid']) < 1 ){
	        AC::$errorNo    =   'TCM001';
	        return  FALSE;
	    }
	    
	    $data['parentId']       =   '0';
	    
	    intval($feedInfo['parentId']) > 0   &&  $data['parentId']   =   $feedInfo['parentId'];
	    
	    $data['uid']            =   $feedInfo['uid'];
	    $data['eUid']           =   $feedInfo['eUid'];
	    $data['eNickname']      =   $feedInfo['eNickname'];
	    $data['authorUid']      =   $feedInfo['authorUid'];
	    $data['authorNickname'] =   $feedInfo['authorNickname'];
	    $data['tid']            =   $feedInfo['tid'];
	    $data['content']        =   $feedInfo['content'];
	    $data['type']           =   $feedInfo['type'];
	    $data['time']           =   AC::SERVER_TIME;
	    $data['status']         =   '0';
	    
	    // 扩展字段,存放楼层以及圈子名字等
	    $extra    =    array(
	            'position' =>    $feedInfo['position'],
	            'positionId'=>   $feedInfo['positionId'],
	            'gname'    =>    $feedInfo['gname'],
	            'extra'    =>    str_replace("\"","\“",$feedInfo['extra']),
	            'gid'      =>    $feedInfo['gid'],
                'extra_uid'         =>  $feedInfo['extra_uid'],
                'extra_nickname'    =>  $feedInfo['extra_nickname'],
	    );
	   // 将中文进行转码
	    $data['extra_context']  =  urldecode(json_encode(array_map("urlencode",$extra)));
	    
	    $key    =   $this->topicFeedKeyPrefix. $feedInfo['uid'];
	    $result =   Storage::addData($key, $data);
	    // 我的评论
	    $tmp    =   $data;
	    $tmp['type'] = 2;
	    $key    =   $this->topicFeedKeyPrefix. $feedInfo['eUid'];
	    $result =   Storage::addData($key, $tmp);
	    
	    return $result;
	}
	
	/**
	 * 获取评论我的列表
	 * @param unknown $info
	 * @return boolean
	 */
	public function getCommentMeList($info){
	    $start    =    0;
	    $length   =    AC::FEED_LIST_DISPLAY_LEN;
	    
	    if (!empty($info['start'])){
	        $start  = intval($info['start']);
	    }
	    if (!empty($info['length'])){
	        $length  = intval($info['length']);
	    }
	    
	    if ($start  <   0)  $start  =   0;
	    $key    =   $this->topicFeedKeyPrefix. $info['uid']. $this->slaveKey;
	    $where  =   array('status'  =>  '0', 'uid' => $info['uid'], 'type'=>1);
	    if  (intval($info['id']) > 0){
	    	$start = '0';
	    	$where =  ' id < '.intval($info['id']).' AND uid ='.intval($info['uid']).' AND status = 0 AND type=1';
	    }
	    $orderBy=   ' id DESC ';
	    $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
	    
	    return $result;
	}
	
	/**
	 * 获取我的评论列表
	 * @param unknown $info
	 * @return Ambigous <unknown, boolean, multitype:>
	 */
	public function getMyCommentsList($info){
		$start    =    0;
		$length   =    AC::FEED_LIST_DISPLAY_LEN;
		if (!empty($info['start'])){
			$start  = intval($info['start']);
		}
		if (!empty($info['length'])){
			$length  = intval($info['length']);
		}
		 
		if ($start  <   0)  $start  =   0;
		$key    =   $this->topicFeedKeyPrefix. $info['uid']. $this->slaveKey;
		$where  =   array('status'  =>  '0', 'eUid' => $info['uid'],'type'=>2);
		if  (intval($info['id']) > 0){
			$start = '0';
			$where =  ' id < '.intval($info['id']).' AND eUid ='.intval($info['uid']).' AND status = 0 AND type = 2';
		}
		$orderBy=   ' time DESC ';
		$result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
		return $result;
	}
	
	/**
	 * 发表评论
	 * @param unknown $info
	 * @return boolean|Ambigous <unknown, boolean>
	 */
	public function postTopicComment($info)/*{{{*/
	{		
		if (intval($info['author_uid']) < 1 ){
		    AC::$errorNo    =   'TCM001';
		    return FALSE;
		}
	    
		$data['content'] = UK::getstr($info['content'], AC::TOPIC_BODY_LENGTH,'',0);
		if (strlen(trim($data['content'])) < 1)
		{
		    AC::$errorNo    =   'TCM004';
		    return FALSE;
		}
		$data['tid'] 		    = 	$info['tid'];
		$data['uid']	 	    = 	$info['uid'];
		$data['nickname']	    =	$info['nickname'];
		$data['author_uid']	    = 	$info['author_uid'];
		$data['author_name']	    =	$info['author_name'];
		$data['time']		    =	AC::SERVER_TIME;
		$data['parentId']	    =	$info['parentId'];
		$data['rUid']	    	    =	$info['rUid'];
		$data['rNickname']	    =	$info['rNickname'];
		$data['attachment']	    =   0;
		$data['gid']	        =   intval($info['gid']);
		isset($info['extend'])    &&    $data['extend']    =    $info['extend'];
		
		$attachment = count($info['attachment']) + count($info['voice']);
		if ($attachment){
		    $data['attachment']    =    $attachment;
		}
		if (intval($data['parentId']) < 1){
		    $data['parentId']    =    '0';
		}
		
		if (intval($data['rUid']) < 1){
		    $data['rUid']    =    '0';
		}
		if (empty($data['rNickname'])){
		    $data['rNickname']    =    '';
		}
		
		$key   		=   $this->topicCommentsKeyPrefix. $data['author_uid'];
		$result		=   Storage::addData($key, $data);
		if (empty($result))
		{
		    AC::$errorNo    =   'TCM002';
		    return  FALSE;
		}
		return  $result;
	}/*}}}*/
	
	/**
	 * 评论点滴
	 * @param unknown $info
	 * @return boolean
	 */
	public function commentDrab ($info) {
	    $data = $this->filterCommentDataOfMysql($info);
	    if (empty($data['author_uid']) || strlen($data['content']) < 1){
	        AC::$errorNo    =   'DCM001';
	        return false;
	    }

	    $key   		=   $this->topicCommentsKeyPrefix. $data['author_uid'];
	    $result		=   Storage::addData($key, $data);
	    if (empty($result)) {
	        AC::$errorNo    =   'DCM002';
	        return  false;
	    }
	    
	    return  $result;
	}
	
	/**
	 * 过滤评论数据
	 * @param unknown $param
	 * @return multitype:number NULL unknown string
	 */
	public function filterCommentDataOfMysql ($param) {
	    $data = array(
	        'uid'            =>  intval($param['uid']),
	        'tid'            =>  intval($param['tid']),
	        'gid'            =>  intval($param['gid']),
	        'author_uid'     =>  intval($param['author_uid']),
	        'content'        =>  UK::getstr($param['content'], AC::TOPIC_BODY_LENGTH),
	        'parentId'       =>  intval($param['parentId']),
	        'rUid'           =>  intval($param['rUid']),
	        'attachment'     =>  intval(count($param['attachmentList']) + count($param['voiceList'])),
	        'nickname'       =>  UK::getstr($param['nickname'], AC::NICKNAMELENGTH, '', 1),
	        'author_name'    =>  UK::getstr($param['author_name'], AC::NICKNAMELENGTH, '', 1),
	        'rNickname'      =>  UK::getstr($param['rNickname'], AC::NICKNAMELENGTH, '', 1),
	        'time'           =>  AC::SERVER_TIME,
	        'url_struct'     =>  isset($param['url_struct']) ? $param['url_struct'] : '',
	        'extend'         =>  isset($param['extend']) ? $param['extend'] : ''
	    );
	    
	    if ($param['diary_create_time'] < AC::$diaryCommentCf['transfer_time'] || $param['entrance'] == 'addCommentInfo') {
	        $data['parentId'] = 0;
	    }
	    return $data;
	}
	
	/**
	 * 获取点滴评论列表
	 * @param unknown $tid
	 * @param unknown $author_uid
	 * @param unknown $page
	 * @param string $sequence
	 * @return boolean|Ambigous <unknown, boolean, multitype:>
	 */
	public function getDrabComments ($tid, $author_uid, $page, $sort = 'all') {
	    list($id, $start, $length) = $page;
	    if (empty($tid) || empty($author_uid)) {
	        AC::$errorNo    =   'DCM001';
	        return  FALSE;
	    }

	    $key    =   $this->topicCommentsKeyPrefix. $author_uid. $this->slaveKey;
	    list($where, $orderBy) = $this->getDrabCommentsBySequence($tid, $sort, $author_uid, $id);
	    
	    $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
	    return  $result;
	}
	
	/**
	 * 获取分页相关条件
	 * @param unknown $tid
	 * @param string $sort
	 * @param number $author_uid
	 * @param number $id
	 * @return multitype:Ambigous <multitype:, string> string
	 */
	private function getDrabCommentsBySequence ($tid, $sort = 'all', $author_uid = 0, $id = 0) {
	    switch ($sort){
	        case 'hot':
	            $where  =   array('tid' => $tid);
	            $orderBy=   ' favorites DESC ';
	            break;
            case 'author':
                $where  =   " `tid` = ".$tid . ' AND `uid` = ' . $author_uid . ' AND `status` = 0';
                if ($id > 0) {
                    $where .= ' AND `position` > '.$id;
                }
	            $orderBy=   ' position ASC ';
                break;
            case 'new':
                $where  =   " `tid` = ".$tid . ' AND `status` = 0';
        	    if ($id > 0) {
        	        $where .= ' AND `position` < '.$id;
        	    }
        	    
        	    $orderBy=   ' position DESC ';
                break;
            default:
                $where  =   " `tid` = ".$tid . ' AND `status` = 0';
                if ($id > 0) {
                    $where .= ' AND `position` > '.$id;
                }
                
                $orderBy=   ' position ASC ';
	    }
	    
	    return array($where, $orderBy);
	}
	
	/**
	 * 查找某条评论信息
	 * @param unknown $info
	 * @return boolean|Ambigous <multitype:, unknown, boolean>
	 */
	public function getCommentUid($info)/*{{{*/
	{
		if (empty($info['position']) || empty($info['tid']) || empty($info['author_uid']))
		{
			AC::$errorNo    =   'TCM001';
			return  FALSE;
		}
	
		$key    =   $this->topicCommentsKeyPrefix. $info['author_uid'];
		$where  =   array('tid'=>$info['tid'], 'position' => $info['position']);
		$result =   Storage::getConditionData($key, $where);
	
		return  $result;
	}/*}}}*/
	/**
	 * 获取话题评论列表
	 * 以楼层分页
	 * @param unknown $info
	 * @return boolean|Ambigous <unknown, boolean, multitype:>
	 */
	public function getTopicCommentList($info, $start, $length)/*{{{*/
	{
		if (intval($info['tid']) < 1 || intval($info['author_uid']) < 1)
		{
			AC::$errorNo    =   'TCM001';
			return  FALSE;
		}
		
		$key    =   $this->topicCommentsKeyPrefix. $info['author_uid']. $this->slaveKey;
		$where  =   array('tid'=>$info['tid']);
		
		if (intval($info['id']) > 0){
			$start = 0;
		    $where = ' position > '.intval($info['id']).' AND tid  = '.intval($info['tid']);
		}
		
		$orderBy=   '';
		$result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
		
		return  $result;
	}/*}}}*/
	
	/**
	 * 只看楼主
	 * @param unknown $info
	 * @return boolean|Ambigous <unknown, boolean, multitype:>
	 */
	public function getLandlordCommentsList($info, $start, $length)/*{{{*/
	{
		if (intval($info['tid']) < 1 || intval($info['author_uid']) < 1)
		{
			AC::$errorNo    =   'TCM001';
			return  FALSE;
		}
	
		$key    =   $this->topicCommentsKeyPrefix. $info['author_uid']. $this->slaveKey;
		$where  =   array('tid'=>$info['tid'],'status'=>0,'uid'=>$info['author_uid']);
	
		if (intval($info['id']) > 0){
			$start = 0;
			$where = ' position > '.intval($info['id']).' AND tid  = '.intval($info['tid']).' AND status = 0 AND uid ='.$info['author_uid'];
		}
		
		$orderBy=   '';
		$result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
	
		return  $result;
	}/*}}}*/
	
	/**
	 * 倒序排
	 * @param unknown $info
	 * @return boolean|Ambigous <unknown, boolean, multitype:>
	 */
	public function getLatestCommentsList($info , $start, $length)/*{{{*/
	{
		if (intval($info['tid']) < 1 || intval($info['author_uid']) < 1)
		{
			AC::$errorNo    =   'TCM001';
			return  FALSE;
		}
	
		$key    =   $this->topicCommentsKeyPrefix. $info['author_uid']. $this->slaveKey;
		$where  =   $where = ' tid  = '.intval($info['tid']).' AND position > 1';
	
		if (intval($info['id']) > 0){
			$start = 0;
			$where = ' position < '.intval($info['id']).' AND tid  = '.intval($info['tid']).' AND position > 1';
		}
	
		$orderBy=   ' time DESC';
		$result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
	
		return  $result;
	}/*}}}*/

	public function getMeCommentList($info)/*{{{*/
	{
		if (empty($info['uid']) || empty($info['topicid']))
		{
			AC::$errorNo    =   'TCM001';
			return  FALSE;
		}

		$start  =   0;
		$length =   AC::COMMENT_LIST_DISPLAY_LEN;
		isset($info['start'])   &&  $start  =   $info['start'];
		isset($info['length'])  &&  $length =   $info['length'];
		if ($start  <   0)  $start  =   0;
		
		$fields =   ' topicid ';
		$where  =   array('uid' => $info['uid']);
		if (!empty($info['id']))   $where  =   ' id < '. $info['id']. ' AND uid = '. $info['uid'];

		$key    =   $this->topicCommentsKeyPrefix. $info['topicid']. $this->slaveKey;
		$orderBy=   ' id DESC ';
		$topicIds =   Storage::getFieldsConditionManyData($key, $fields, $where, $orderBy, $start, $length);
		$result = array_unique($topicIds);
		if (empty($result)) return null;
		
		return  $result;
	}/*}}}*/
	
	public function removeTopicComment($info)/*{{{*/
	{
		if (empty($info['position']) || empty($info['tid']) || empty($info['author_uid']))
		{
			AC::$errorNo    =   'TCM001';
			return  FALSE;
		}
		
		$data   =   array('status' => 1);
		$key    =   $this->topicCommentsKeyPrefix. $info['author_uid'];
		$where  =   array('position' => $info['position'],'tid'=> $info['tid']);
		$result =   Storage::setConditionData($key, $data, $where);
		if (empty($result))
		{
			AC::$errorNo    =   'TCM003';
			return FALSE;
		}
		return  $result;
	}/*}}}*/

	// 删除用户的所有评论(话题)
	public function removeTopicComments($info)/*{{{*/
	{
		for($i=0;$i<=31;$i++)
		{
			$sql        = 	"Update xxtShare.topiccomments_".$i." SET status = 1 WHERE uid = ".$info['uid']." AND position > 1";
			$keyClient  =   $this->topicCommentsKeyPrefix. $i;
			$result     =   Storage::fetchDbSentenceByClient($keyClient, $sql, 2);
		}
		return  true;
	}
	
	//================================================== new ================================================
	/**
	 * 只看楼主
	 * @param unknown $tid
	 * @param unknown $author_uid
	 * @param number $id
	 * @param number $start
	 * @param number $length
	 * @return boolean|Ambigous <unknown, boolean, multitype:>
	 */
	public function getAuthorComments ($tid, $author_uid, $id = 0, $start = 0, $length = 20) {
	    if (empty($tid) || empty($author_uid)) {
	        AC::$errorNo    =   'TCM001';
	        return  FALSE;
	    }
	
	    $key    =   $this->topicCommentsKeyPrefix. $author_uid. $this->slaveKey;
	    $where  =   array('tid' => $tid,'status' => 0,'uid'=> $author_uid);
	
	    if ($id){
	        $start = 0;
	        $where = ' position > '.$id.' AND tid  = '.$tid.' AND status = 0 AND uid ='.$author_uid;
	    }
	
	    $orderBy=   '';
	    $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
	
	    return  $result;
	}
	
	/**
	 * 最新评论
	 * @param unknown $tid
	 * @param unknown $author_uid
	 * @param number $id
	 * @param number $start
	 * @param number $length
	 * @return boolean|Ambigous <unknown, boolean, multitype:>
	 */
	public function getNewComments ($tid, $author_uid, $id = 0, $start = 0, $length = 20) {
	    if (empty($tid) || empty($author_uid)) {
	        AC::$errorNo    =   'TCM001';
	        return  FALSE;
	    }
	
	    $key    =   $this->topicCommentsKeyPrefix. $author_uid. $this->slaveKey;
	    $where  =   $where = ' tid  = '.$tid.' AND position > 1';
	
	    if ($id){
	        $start = 0;
	        $where = ' position < '.$id.' AND tid  = '.$tid.' AND position > 1';
	    }
	
	    $orderBy=   ' time DESC';
	    $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
	
	    return  $result;
	}
	
	/**
	 * 默认话题评论
	 * @param unknown $tid
	 * @param unknown $author_uid
	 * @param number $id
	 * @param number $start
	 * @param number $length
	 * @return boolean|Ambigous <unknown, boolean, multitype:>
	 */
	public function getTopicComments ($tid, $author_uid, $id = 0, $start = 0, $length = 20) {
	    if (empty($tid) || empty($author_uid)) {
	        AC::$errorNo    =   'TCM001';
	        return  FALSE;
	    }
	
	    $key    =   $this->topicCommentsKeyPrefix. $author_uid. $this->slaveKey;
	    $where  =   array('tid' => $tid);
	
	    if (intval($info['id']) > 0){
	        $start = 0;
	        $where = ' position > '.$id.' AND tid  = '.$tid;
	    }
	
	    $orderBy=   '';
	    $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
	
	    return  $result;
	}
	
	/**
	 * 获取单挑评论信息
	 * @param unknown $position
	 * @param unknown $tid
	 * @param unknown $author_uid
	 * @return boolean|Ambigous <multitype:, unknown, boolean>
	 */
	public function getCommentInfo ($position, $tid, $author_uid) {
	    if (empty($position) || empty($tid) || empty($author_uid)) {
	        AC::$errorNo    =   'TCM001';
	        return  FALSE;
	    }
	
	    $key    =   $this->topicCommentsKeyPrefix. $author_uid;
	    $where  =   array('position' => $position,'tid' => $tid);
	    $result =   Storage::getConditionData($key, $where);
	
	    return  $result;
	}


    /**
     * 根据parentId获取评论
     * @param $parentId
     * @param $tid
     * @param $author_uid
     * @return array|bool
     */
	public function getCommentListByParentId($parentId, $tid, $author_uid) {
        if (empty($parentId) || empty($tid) || empty($author_uid)) {
            AC::$errorNo    =   'TCM001';
            return  FALSE;
        }

        $key    =   $this->topicCommentsKeyPrefix. $author_uid;
        $where  =   array('parentId' => $parentId,'tid' => $tid);
        $result =   Storage::getConditionManyData($key, $where);

        return  $result;
    }

    /**
     * 更新引用楼层的评论附件
     * @param $comments
     * @return bool
     */
    public function updateComments($comments) {
	    if(empty($comments)) return true;
	    foreach ($comments as $comment) {
            $commentInfo = $this->getCommentInfo($comment['position'], $comment['tid'], $comment['author_uid']);
            if(empty($commentInfo) || empty($commentInfo['extend'])) continue;
            $extend = json_decode($commentInfo['extend'], true);
            if(empty($extend['parentComment'])) continue;
            $extend['parentComment']['content'] = '该评论已被删除';
            $info = [
                'position'  =>  $comment['position'],
                'tid'       =>  $comment['tid'],
                'author_uid'=>  $comment['author_uid'],
                'extend'    =>  UK::var_json_encode($extend)
            ];
            $this->updateTopicComment($info);
        }
    }

    /**
     * 更新评论
     * @param $info
     * @return bool|int|resource
     */
    public function updateTopicComment($info)/*{{{*/
    {
        if (empty($info['position']) || empty($info['tid']) || empty($info['author_uid']))
        {
            AC::$errorNo    =   'TCM001';
            return  FALSE;
        }
        $data = [];
        isset($info['status']) && $data['status'] = $info['status'];
        isset($info['extend']) && $data['extend'] = $info['extend'];

        if(empty($data)){
            return true;
        }
        $key    =   $this->topicCommentsKeyPrefix. $info['author_uid'];
        $where  =   array('position' => $info['position'],'tid'=> $info['tid']);
        $result =   Storage::setConditionData($key, $data, $where);
        if (empty($result))
        {
            AC::$errorNo    =   'TCM003';
            return FALSE;
        }
        return  $result;
    }/*}}}*/
}